package com.gitee.dolt.core.validator;

import com.gitee.dolt.core.exception.ValidParamException;
import com.gitee.dolt.core.util.SpringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author LYH
 */
public class ValidatorUtil {
    private static Validator validator;

    static {
        validator = SpringUtils.getBean(Validator.class);
    }

    public static <T> void validate(T obj, Class<?>... groups) {
        Set<ConstraintViolation<T>> result = validator.validate(obj, groups);
        if (!result.isEmpty()) {
            ConstraintViolation<T> constraintViolation = result.iterator().next();
            throw new ValidParamException(constraintViolation.getPropertyPath().toString(), constraintViolation.getInvalidValue(),
                    constraintViolation.getMessage());
        }
    }
}
